/**
 * Created by voidsun on 15/1/30.
 */
(function ($) {
    var Daffodil = function(element, options){
        this.$element = $(element);
        this.options = options;
        this.isShown = false;
        this.searchParam = "";
        this.$daffodil = null;
        this.$selectList = null;
        this.$search = null;
        this.$dataList = null;
        this.$submit = null;
        this.canLoad = true;
        this.pageInfo = {
            pageSize : this.options.pageSize,
            targetPage : 1
        };
        this.options.infoWidth = this.options.width - 90;
        this.init();
    };
    Daffodil.prototype = {
        constructor : Daffodil,
        init : function(){
            var that = this;
            var html = '<div class="_daffodil" > \
                <input class="_search" placeholder="'+this.options.searchHolder+'">\
                <div style="display:none" class="_selectList"></div>\
                <div class="_dataList"></div>\
                </div>';
            $("body").append(html);
            this.$daffodil = $("body>div").last();
            this.$search = this.$daffodil.children("._search");
            this.$selectList = this.$daffodil.children("._selectList");
            this.$dataList = this.$daffodil.children("._dataList");
            this.$element.on("mousedown", function(event){
                that.show(event, that);
            });
            $(document).on("mousedown", function(event){
                that.hide(event, that);
            });
            this.$search.on("keyup", function(event){
                if(event.keyCode == "13"){
                    that.$dataList.html("");
                    that.pageInfo.targetPage = 1;
                    that.searchParam = $(this).val().trim();
                    that.load(null, that);
                }
            });
            this.$dataList.on("mousedown", "._data", function(event){
                $(this).removeClass("_relief");
            });
            this.$dataList.on("mouseup", "._data", function(event){
                $(this).addClass("_relief");
                that.toggleData($(this).attr("data-id"), that);
            });
            this.resize(this);
            this.$daffodil.css("width", this.options.width);
            this.$dataList.css("height", this.options.height - 30);
            if(this.options.lazyLoad == "true"){
                this.$dataList.on("scroll", function(event){
                    if($(this).scrollTop() + $(this).innerHeight() > $(this)[0].scrollHeight * 0.9 && that.canLoad){
                        that.pageInfo.targetPage = that.pageInfo.targetPage + 1;
                        that.load(null, that);
                    }
                });
            }
            if(this.options.singleType == "false"){
                this.$selectList.on("mouseup", "._select_data", function(event){
                    that.toggleData($(this).attr("data-id"), that);
                }).on("mouseup", "._submit", function(event){
                    that.returnData(that);
                });
            }
            if(this.options.styleList){
                $.each(this.options.styleList, function(cssKey, cssVal){
                    that.$daffodil.css(cssKey, cssVal);
                });
            }
        },
        show : function(event, that){
            that = that || this;
            if(that.isShown) return;
            if(event)event.stopPropagation();
            this.load("", this);
            var offset = this.$element.offset();
            var height = Number(this.$element.outerHeight());
            that.$daffodil.css("top", Number(offset.top) + height);
            that.$daffodil.css("left", offset.left);
            if(that.options.singleType == "false"){
                that.$submit = DaffodilGlobal.buildSubmitBtn(that.$selectList, that.options);
            }
            that.$daffodil.fadeIn(500);
            that.isShown = true;
        },
        hide : function(event, that){
            that = that || this;
            if(that.isShown && (!event || $(event.target).closest("._daffodil").length == 0)) {
                that.$search.val("");
                that.$selectList.html("");
                that.resize(that);
                that.$dataList.scrollTop(0);
                that.$daffodil.fadeOut(500);
                that.isShown = false;
            }
        },
        load : function(param, that){
            that = that || this;
            param = param || that.searchParam;
            that.canLoad = false;
            DaffodilGlobal.buildAlertInfo(that.$dataList, that.options.searchInfo);
            var postData = {};
            postData.pageInfo = that.pageInfo;
            postData[that.options.paramName] = param;
            $.ajax({
                url : that.options.url,
                type : "POST",
                dataType : "json",
                data : postData,
                success : function(data){
                    if(data.err || !data.dataJson)
                        return DaffodilGlobal.buildAlertInfo(that.$dataList, that.options.errorInfo);
                    DaffodilGlobal.buildDataList(data.dataJson, that.$dataList, that.options);
                    if(data.dataJson.length < that.pageInfo.pageSize) {
                        that.canLoad = false;
                        that.pageInfo.targetPage = that.pageInfo.targetPage + 1;//防止下次展开时再次加载最后一页
                        return DaffodilGlobal.buildAlertInfo(that.$dataList, that.options.finishInfo);
                    }
                    DaffodilGlobal.buildAlertInfo(that.$dataList, that.options.searchInfo);
                    that.canLoad = true;
                },
                error : function(){
                    DaffodilGlobal.buildAlertInfo(that.$dataList, that.options.errorInfo);
                }
            });
        },
        toggleData : function(dataId, that){
            that = that || this;
            var fullName = that.$daffodil.find("#_daffodil_name_"+dataId).text().trim();
            if(that.options.singleType == "true"){
                return that.returnData(that, {id: dataId, name: fullName});
            }
            var showName = fullName;
            if(fullName.length > 5)showName = showName.substr(0, 4) + "...";
            var selectData = that.$selectList.find("#_daffodil_select_"+dataId);
            if(selectData.length > 0){
                selectData.remove();
            }else{
                DaffodilGlobal.buildSelectData(dataId, showName, fullName, that.$submit);
            }
            that.resize(that);
        },
        resize : function(that){
            that = that || this;
            var fixHeight = 0;
            if(that.$selectList.children("._select_data").length == 0) {
                that.$selectList.hide();
                fixHeight = -20;
            }else{
                that.$selectList.show();
                fixHeight = that.$selectList.height();
            }
            that.$daffodil.css("height", that.options.height + 30 + fixHeight);
        },
        returnData : function(that, data){
            that = that || this;
            if(!data) {
                data = [];
                $(that.$selectList.children("._select_data")).each(function () {
                    data.push({id: $(this).attr("data-id"), name: $(this).attr("data-name")});
                });
            }
            that.hide(null, that);
            that.options.dataCallBack(data);
        }
    };
    $.fn.daffodil = function(options){
        var daffodil = this.data("_daffodil");
        if(!daffodil){
            daffodil = new Daffodil(this, $.extend({}, DaffodilGlobal.defaultOptions, options));
            this.data("_daffodil", daffodil);
        }
        return daffodil;
    };
    var DaffodilGlobal = {
        defaultOptions : {
            pageSize : 10,
            lazyLoad : "true",
            height : 400,
            width : 350,
            singleType : "false",
            searchInfo : "正在努力的为您加载喵……",
            finishInfo : "已经找不到更多了喵……",
            errorInfo : "服务器坏掉了喵……",
            searchHolder : "随便输入点什么，回车进行查询喵",
            submitInfo : "就选这些吧喵"
        },
        buildDataList : function(dataArray, $element, options){
            var html = [];
            $.each(dataArray, function(idx, data){
                var dataId = data[options.dataId];
                html.push('<div data-id="'+dataId+'" id="_daffodil_'+dataId+'" class="_data _relief">');
                html.push('<div class="_pull_left"><img class="_image" src="'+ data[options.showImg]+'"></div>');
                html.push('<div class="_pull_left _padding_left _word_break" style="width:'+options.infoWidth+'px">');
                html.push('<div id="_daffodil_name_'+dataId+'" class="_text_primary">');
                html.push(data[options.showName] + '</div>');
                html.push('<div>'+data[options.showInfo]+'</div>');
                html.push('</div>');
                html.push('</div>');
            });
            $element.append(html.join(''));
        },
        buildSelectData : function(id, name, fullName, $element){
            var html = '<span class="_select_data" data-name="'+fullName+'" data-id="'+id+'" id="_daffodil_select_'+id+'">'
                + name + '</span>';
            $element.before(html);
        },
        buildAlertInfo : function($element, info){
            $element.children("._info").remove();
            $element.append('<div class="_info">'+info+'</div>');
        },
        buildSubmitBtn : function($element, options){
            $element.append('<span class="_submit">'+options.submitInfo+'</span>');
            return $element.children().first();
        }
    };
})(jQuery); 